<template>
    <div class="container">
        <header>
            <el-menu
                    class="el-menu-demo"
                    mode="horizontal"
                    :ellipsis="false"
            >
                <el-menu-item index="0">LOGO</el-menu-item>
                <div class="flex-grow"/>
                <el-sub-menu index="1">
                    <template #title>
                        <el-avatar :src="avatarComputed"/>
                    </template>
                    <el-menu-item index="1" v-if="store.getters['customer/getCutomerId']" @click="logoutHandler">退出
                    </el-menu-item>
                    <el-menu-item index="2" v-else @click="showLoginDialog">登陆</el-menu-item>
                    <router-link to="/business/login">
                        <el-menu-item>商家后台</el-menu-item>
                    </router-link>
                    <router-link to="/admin/login">
                        <el-menu-item>管理后台</el-menu-item>
                    </router-link>
                </el-sub-menu>
            </el-menu>
        </header>
        <div class="body-container">
            <div>
                <h1 style="margin-left: 16px;font-weight: bold">每日新品</h1>
                <div class="random-container">
                    <div class="random-business">
                        <el-carousel indicator-position="outside" height="500px">
                            <el-carousel-item v-for="item in datas.randomBusiness" :key="item">
                                <div class="random-business-item">
                                    <img class="img-business-cover" fit="fill" :src="item.cover" alt=""/>
                                    <div class="business-info">
                                        <h1>{{ item.name }}</h1>
                                        <p style="text-align: center">{{ item.address }}</p>
                                    </div>
                                </div>
                            </el-carousel-item>
                        </el-carousel>
                    </div>
                    <div class="random-goods">
                        <div v-for="(item,index) in datas.randomFoodData" :key="index">
                            <GoodsCard :data="item" :key="index"/>
                        </div>
                    </div>
                </div>
            </div>
            <div class="businesses-container">
                <h1 class="title">店家小聚</h1>
                <div class="businesses-container-inner">
                    <el-row :gutter="20" style="width: 100%">
                        <el-col :span="12" v-for="(item,index) in datas.allBusinessData" :key="index">
                            <BusinessCard :id="item.id"
                                          :address="item.address"
                                          :cover="item.cover"
                                          :name="item.name"
                                          :phone="item.phone"
                                          @ChoodsEvent="chooseEventHandler"
                            />
                        </el-col>
                    </el-row>
                </div>
                <div class="btn-more-business-box">
                    <el-button class="btn-more-business" @click="getMoreBusinessHandler()">查看更多</el-button>
                </div>
            </div>
        </div>
        <el-drawer v-model="drawerVisable" direction="btt" size="70%">
            <template #header>
                <h3>{{ orderData.businessInfo.name }}</h3>
            </template>
            <template #default>
                <div class="info">

                    <el-tabs type="border-card">
                        <el-tab-pane v-for="(item,index) in datas.AllBusinessGoods" :label="item.name">
                            <div style="display: flex">
                                <div v-for="(i,key) in item.goodsMessageList" :key="key">
                                    <FoodCard :data="i"/>
                                </div>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                    <div style="text-align: right;padding: 16px">
                        <el-button type="primary" @click="bugHandler">购买</el-button>
                    </div>
                </div>
            </template>
        </el-drawer>

        <BaseFormDialog title="" :visible="loginDialogVisable" :footer-visable="false">
            <template #FormContent>
                <el-tabs type="border-card">
                    <el-tab-pane label="登陆">
                        <el-form ref="ruleFormRef" class="login-form" autocomplete="on"
                                 :model="customerdata.loginData"
                                 :rules="loginFormRules"
                                 label-position="top" status-icon>
                            <el-form-item label="用户名" prop="userName">
                                <el-input placeholder="请输入用户名" v-model="customerdata.loginData.userName"
                                          name="userName"
                                          type="text"/>
                            </el-form-item>
                            <el-form-item label="密码" prop="password">
                                <el-input placeholder="请输入密码" v-model="customerdata.loginData.password"
                                          name="password"
                                          show-password
                                          type="password"/>
                            </el-form-item>
                            <el-form-item label="验证码" prop="code">
                                <el-row justify="space-between" style="width: 100%">
                                    <el-col :span="12">
                                        <el-input placeholder="验证码" v-model="customerdata.loginData.code" name="code"
                                                  type="text"/>
                                    </el-col>
                                    <el-col :span="12" class="code-box">
                                        <el-image class="code"
                                                  :src="codeImage"
                                                  v-loading="codeLoading"
                                                  @click="loadCaptcha()"
                                        ></el-image>
                                    </el-col>
                                </el-row>
                            </el-form-item>
                            <el-row justify="center">
                                <el-button type="primary" @click="LoginHandler(ruleFormRef)">提交</el-button>
                            </el-row>
                        </el-form>
                    </el-tab-pane>
                    <el-tab-pane label="注册">
                        <el-form ref="ruleFormRef1" class="login-form"
                                 autocomplete="on"
                                 :model="customerdata.registeryData"
                                 :rules="registeryCustomerRulestomer"
                                 label-position="top" status-icon>
                            <el-form-item prop="cover">
                                <el-upload
                                        name="file"
                                        method="post"
                                        class="avatar-uploader"
                                        action="http://127.0.0.1:8080/api/common/uploud/avatar"
                                        :show-file-list="false"
                                        :on-success="handleAvatarSuccess"
                                >
                                    <el-image v-if="customerdata.registeryData.avatar"
                                              :src="customerdata.registeryData.avatar" class="avatar" alt=""/>
                                    <el-icon v-else class="avatar-uploader-icon">
                                        <Plus/>
                                    </el-icon>
                                </el-upload>
                            </el-form-item>
                            <el-form-item label="用户名" prop="userName">
                                <el-input placeholder="请输入用户名" v-model="customerdata.registeryData.userName"
                                          name="userName" type="text"/>
                            </el-form-item>
                            <el-form-item label="密码" prop="password">
                                <el-input placeholder="请输入密码" v-model="customerdata.registeryData.password"
                                          name="password" show-password
                                          type="password"/>
                            </el-form-item>
                            <el-form-item label="电话" prop="tel">
                                <el-input placeholder="请输入用户名" v-model="customerdata.registeryData.tel"
                                          name="tel" type="text"/>
                            </el-form-item>
                            <el-form-item label="地址" prop="address">
                                <el-input placeholder="请输入店铺地址" v-model="customerdata.registeryData.address"
                                          name="address" type="text"/>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="registeryHandler(ruleFormRef1)">注册</el-button>
                            </el-form-item>
                        </el-form>
                    </el-tab-pane>
                </el-tabs>
            </template>
        </BaseFormDialog>
    </div>
</template>

<script setup>
import "@/utils/ribbon"
import {computed, onMounted, reactive, ref} from "vue";
import {getRandomGoods} from "@/api/Goods";
import GoodsCard from "@/views/home/component/GoodsCard.vue";
import {getAllBusiness, getAllBusinessGoods, getBusinessInfo, getRandomBusiness} from "@/api/business";
import BusinessCard from "@/views/home/component/BusinessCard.vue";
import FoodCard from "@/views/home/component/FoodCard.vue";
import store from "@/store/Index";
import {createOrder} from "@/api/order";
import {ElMessage} from "element-plus";
import BaseFormDialog from "@/components/BaseFormDialog/Index.vue"
import {loginFormRules} from "@/rules/UserFormRules";
import {getCaptcha} from "@/api/user";
import {Plus} from "@element-plus/icons-vue";
import {customerLogin, customerRegistery, getCustomreInfo} from "@/api/customer";
import {setToken} from "@/utils/auth";
import {registeryCustomerRulestomer} from "@/rules/customerRules";

let codeImage = ref();
const loginDialogVisable = ref(false);
const ruleFormRef = ref(null);
const ruleFormRef1 = ref(null);
const codeLoading = ref(true);
const drawerVisable = ref(false);
// const avatarComputed = computed({
//     get() {
//
//         return store.getters["customer/getAvatar"]
//     },
//     set(v) {
//         console.log(v);
//         store.dispatch("customer/setCustomerInfo", v)
//     }
// })
const  avatarComputed = computed(() => store.state.customer.avatar);
const datas = reactive(({
    randomFoodData: [],
    randomBusiness: [],
    allBusinessData: [],
    AllBusinessGoods: []
}))
const pageConfig = reactive({
    pageNum: 1,
    pageSize: 4
})
const orderData = reactive({
    businessInfo: {
        id: '',
        name: ''
    },
    goods: []
})
const customerdata = reactive({
    loginData: {
        userName: '',
        password: '',
        key: '',
        code: ''
    },
    registeryData: {
        userName: "",
        password: "",
        avatar: '',
        address: "",
        tel: ""
    }
})
onMounted(() => {
    getRandomGoods().then((response) => {
        datas.randomFoodData = response.data;
    })
    getRandomBusiness().then((response) => {
        datas.randomBusiness = response.data
    })
    getAllBusinessHandler();
})

function getAllBusinessHandler() {
    getAllBusiness(pageConfig).then((response) => {
        datas.allBusinessData = response.data.rows;
    })
}

function getMoreBusinessHandler() {
    pageConfig.pageSize += 3;
    getAllBusinessHandler();
}

function chooseEventHandler(prop) {
    drawerVisable.value = true;
    store.dispatch("Goods/clearFood")
    orderData.businessInfo = prop;
    getAllBusinessGoods(prop.id).then((response) => {
        datas.AllBusinessGoods = response.data;
    })
}

function bugHandler() {
    if (!store.getters["customer/getCutomerId"]){
        ElMessage({
            message: "抱歉您还没有登陆",
            type: "warning"
        })
        return;
    }
    if (store.getters["Goods/getGoodsList"].length>0){
        createOrder({
            customId: store.getters["customer/getCutomerId"],
            businessId: orderData.businessInfo.id,
            goodsList: store.getters["Goods/getGoodsList"]
        }).then((response) => {
            ElMessage({
                message: "购买成功",
                type: "success"
            })
        })
    }else {
        ElMessage({
            message: "没有购买任何商品，无法支付",
            type: "warning"
        })
    }
}


function loadCaptcha() {
    getCaptcha().then(response => {
        codeImage.value = response.data.image;
        customerdata.loginData.key = response.data.key
        codeLoading.value = false;
    })
}


async function LoginHandler(formEl) {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
            if (valid) {
                const response = await customerLogin(customerdata.loginData);
                setToken(response.data.token)
                await store.dispatch("user/setRole", "customer")
                const infoResponse = await getCustomreInfo();

                avatarComputed.value = infoResponse.data;
                console.log(avatarComputed)
                await store.dispatch("customer/setCustomerInfo", infoResponse.data);
                ElMessage({
                    message: '登录成功',
                    type: 'success',
                    duration: 1000
                })
                loginDialogVisable.value = false;
            } else {
                ElMessage({
                    message: '请完成所有必填字段',
                    type: 'warning',
                    duration: 5 * 1000
                })
            }
        }
    )
}

function logoutHandler() {
    store.dispatch("customer/logout")
    ElMessage({
        message: '退出成功',
        type: 'success'
    })
}

async function registeryHandler(formEl) {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
            if (valid) {
                customerRegistery(customerdata.registeryData).then(response => {
                    ElMessage({
                        message: '注册成功,请前往登陆',
                        type: 'success',
                        duration: 1000
                    })
                })
                loginDialogVisable.value = false;
            } else {
                ElMessage({
                    message: '请完成所有必填字段',
                    type: 'warning',
                    duration: 5 * 1000
                })
            }
        }
    )
}

function handleAvatarSuccess(response, uploadFile) {
    customerdata.registeryData.avatar = response.data;
}

function showLoginDialog() {
    loadCaptcha();
    if (loginDialogVisable.value) {
        loginDialogVisable.value = false;
    } else {
        loginDialogVisable.value = true;
    }
}
</script>

<style scoped>
.flex-grow {
    flex-grow: 1;
}

.container {
    width: 100%;
    height: 100%;
}

.body-container {
    width: 80%;
    margin: 8px auto;
}


.random-container {
    width: 100%;
    display: flex;
}

.random-business {
    width: 45%;
    padding: 16px;
}

.random-goods {
    width: 55%;
    padding: 8px;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}

.el-carousel__item h3 {
    color: #475669;
    font-size: 14px;
    opacity: 0.75;
    line-height: 200px;
    margin: 0;
}

.img-business-cover {
    width: 100%;
    height: 100%;
    object-fit: fill;
}

.random-business-item {
    position: relative;
}

.business-info {
    color: white;
    position: absolute;
    bottom: 10%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.title {
    font-weight: bold;
}

.businesses-container {
    padding: 16px;
}

.btn-more-business-box {
    margin-top: 16px;
    text-align: center;
}

.businesses-container-inner {
    display: flex;
    flex-wrap: wrap;
}

.businesses-container-inner .el-col:nth-child(2n-1) :deep(.business-card-inner) .business-info > div {
    justify-content: right;

    flex-direction: row-reverse;
}


.businesses-container-inner .el-col:nth-child(2n-1) .business-card:hover {
    transform: translateX(-50px);
}

.businesses-container-inner .el-col:nth-child(2n) .business-card:hover {
    transform: translateX(50px);
}

.businesses-container-inner .el-col:nth-child(2n) :deep(.business-card-inner) {
    flex-direction: row-reverse;
}

.businesses-container-inner .el-col:nth-child(2n) :deep(.business-card-inner) .business-info {
    text-align: left;
}

.info {
    width: 100%;
    height: 100%;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
}

:deep(.el-form-item__content) {
    justify-content: center;
}

:deep(.avatar) {
    width: 100px;
    height: 100px;
    border-radius: 50px;
}

:deep(.el-upload) {
    border: 2px solid #d9d9d9;
    border-radius: 50px;
}
.random-business-item{
    height: 100%;
}
</style>